package com.wfh.picture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wfh.picture.api.aliyunai.AliYunAiApi;
import com.wfh.picture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.wfh.picture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.wfh.picture.common.DeleteRequest;
import com.wfh.picture.exception.BusinessException;
import com.wfh.picture.exception.ErrorCode;
import com.wfh.picture.exception.ThrowUtils;
import com.wfh.picture.manager.ObsManager;
import com.wfh.picture.manager.upload.BasePictureUploadTemplate;
import com.wfh.picture.manager.upload.BasePictureUploadTemplateImpl;
import com.wfh.picture.manager.upload.BasePictureUrlUploadTemplateImpl;
import com.wfh.picture.mapper.PictureMapper;
import com.wfh.picture.model.dto.file.UploadPictureResult;
import com.wfh.picture.model.dto.picture.*;
import com.wfh.picture.model.entity.Picture;
import com.wfh.picture.model.entity.Space;
import com.wfh.picture.model.entity.User;
import com.wfh.picture.model.enums.PictureReviewStatusEnum;
import com.wfh.picture.model.vo.PictureVO;
import com.wfh.picture.model.vo.UserVO;
import com.wfh.picture.service.PictureService;
import com.wfh.picture.service.SpaceService;
import com.wfh.picture.service.UserService;
import com.wfh.picture.utils.CalculateColorUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author lenovo
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-05-09 14:00:51
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{


    @Resource
    private BasePictureUploadTemplateImpl basePictureUploadTemplate;


    @Resource
    private BasePictureUrlUploadTemplateImpl basePictureUrlUploadTemplate;

    @Resource
    private UserService userService;

    @Resource
    private ObsManager obsManager;

    @Resource
    private SpaceService spaceService;

    /**
     * 上传图片
     * @param inputSource
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR);
        // 判断是新增还是删除
        Long id = null;
        if (pictureUploadRequest != null){
            id = pictureUploadRequest.getId();
        }
        assert pictureUploadRequest != null;
        Long spaceId = pictureUploadRequest.getSpaceId();
        if (spaceId != null){
            Space space = spaceService.getById(spaceId);
            if (space == null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间不存在");
            }
            // 只有空间的管理员才可以修改
            if (!(Objects.equals(loginUser.getId(), space.getUserId()))){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有权限编辑空间");
            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()){
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }

        }
        // 如果是更新
        if (id != null){
            Picture oldPicture = this.getById(id);
            ThrowUtils.throwIf(oldPicture == null, ErrorCode.PARAMS_ERROR, "图片不存在");
            // 仅仅本人和管理员可以编辑
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            /*boolean exists = this.lambdaQuery()
                    .eq(Picture::getId, id)
                    .exists();
            ThrowUtils.throwIf(!exists, ErrorCode.PARAMS_ERROR, "图片不存在");*/

            // 校验空间是否一致
            if (spaceId == null){
                if (oldPicture.getSpaceId() != null){
                    spaceId = oldPicture.getSpaceId();
                }
            }else {
                // 传了spaceid，必须和原图片的空间id一致
                if (ObjUtil.notEqual(spaceId, oldPicture.getSpaceId())){
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间id不一致");
                }
            }
        }
        // 上传图片,用户id划分目录
        String uploadPathPrefix;
        if (spaceId == null){
            // 公共图库
            uploadPathPrefix = String.format("public/%s", loginUser.getId());
        }else {
            // 私有图库
            uploadPathPrefix = String.format("private/%s", loginUser.getId());
        }

        // 根据inputSource的类型区分上传方式
        BasePictureUploadTemplate basePictureUpload = basePictureUploadTemplate;
        if (inputSource instanceof String){
            basePictureUpload = basePictureUrlUploadTemplate;
        }
        UploadPictureResult uploadPictureResult = basePictureUpload.uploadPicture(inputSource, uploadPathPrefix);
        // 构造入库对象
        String url = uploadPictureResult.getUrl();
        String picName = uploadPictureResult.getPicName();
        Long picSize = uploadPictureResult.getPicSize();
        int picWidth = uploadPictureResult.getPicWidth();
        int picHeight = uploadPictureResult.getPicHeight();
        Double picScale = uploadPictureResult.getPicScale();
        String picFormat = uploadPictureResult.getPicFormat();
        String thumbnailUrl = uploadPictureResult.getThumbnailUrl();
        Picture picture = new Picture();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())){
            picName = pictureUploadRequest.getPicName();
        }
        picture.setUrl(url);
        picture.setName(picName);
        picture.setPicSize(picSize);
        picture.setPicWidth(picWidth);
        picture.setPicHeight(picHeight);
        picture.setPicScale(picScale);
        picture.setSpaceId(spaceId);
        picture.setPicFormat(picFormat);
        picture.setUserId(loginUser.getId());
        picture.setThumbnailUrl(thumbnailUrl);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(loginUser, userVO);
        PictureVO pictureVO = PictureVO.objToVo(picture);
        pictureVO.setUserVO(userVO);
        fillReviewParams(picture, loginUser);
        // 操作数据库
        PictureService pictureServiceProxy = (PictureService) AopContext.currentProxy();
        // 如果id不为空，表示更新
        if (id != null){
            picture.setId(id);
            picture.setEditTime(new Date());
        }

        // 更新额度
        boolean saved = pictureServiceProxy.saveOrUpdate(picture);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "数据保存失败");
        boolean update = spaceService.lambdaUpdate()
                .eq(Space::getId, spaceId)
                .setSql("totalSize = totalSize +" + picture.getPicSize())
                .setSql("totalCount = totalCount + 1")
                .update();
        if (!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据保存失败");
        }
        return PictureVO.objToVo(picture);
    }

    /**
     * 获取包装类
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUserVO(userVO);
        }
        return pictureVO;
    }

    /**
     * 校验图片
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }


    /**
     * 分页获取图片封装
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        // 1. 关联查询用户信息
        Set<Long> userIdSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // 2. 填充信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            pictureVO.setUserVO(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);
        return pictureVOPage;
    }


    /**
     * 获取查询对象
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public LambdaQueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        String searchText = pictureQueryRequest.getSearchText();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        Long userId = pictureQueryRequest.getUserId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        LambdaQueryWrapper<Picture> lambdaQueryWrapper = new LambdaQueryWrapper<Picture>();
        // 从多字段中查询
        if (StrUtil.isNotBlank(searchText)){
            lambdaQueryWrapper
                    .and(qw -> {
                        qw.like(Picture::getName, searchText)
                                .or()
                                .like(Picture::getIntroduction, searchText);
                    });
        }
        lambdaQueryWrapper.eq(ObjUtil.isNotEmpty(id), Picture::getId, id)
                .eq(ObjUtil.isNotEmpty(userId), Picture::getUserId, userId)
                .isNull(nullSpaceId, Picture::getSpaceId)
                .eq(ObjUtil.isNotEmpty(spaceId), Picture::getSpaceId, spaceId)
                .like(StrUtil.isNotBlank(name), Picture::getName, name)
                .like(StrUtil.isNotBlank(introduction), Picture::getIntroduction, introduction)
                .like(StrUtil.isNotBlank(picFormat), Picture::getPicFormat, picFormat)
                .like(StrUtil.isNotBlank(reviewMessage), Picture::getReviewMessage, reviewMessage)
                .eq(StrUtil.isNotBlank(category), Picture::getCategory, category)
                .ge(ObjUtil.isNotEmpty(startEditTime), Picture::getEditTime, startEditTime)
                .lt(ObjUtil.isNotEmpty(endEditTime), Picture::getEditTime, endEditTime)
                .eq(ObjUtil.isNotEmpty(reviewStatus), Picture::getReviewStatus, reviewStatus)
                .eq(ObjUtil.isNotEmpty(reviewerId), Picture::getReviewerId, reviewerId)
                .eq(ObjUtil.isNotEmpty(picWidth), Picture::getPicWidth, picWidth)
                .eq(ObjUtil.isNotEmpty(picHeight), Picture::getPicHeight, picHeight)
                .eq(ObjUtil.isNotEmpty(picScale), Picture::getPicSize, picSize)
                .eq(ObjUtil.isNotEmpty(picScale), Picture::getPicScale, picScale);
        // json数组查询
        if (CollUtil.isNotEmpty(tags)){
            for (String tag : tags) {
                lambdaQueryWrapper.like(Picture::getTags, "\"" + tag + "\"");
            }
        }
        return lambdaQueryWrapper;
    }

    /**
     * 图片审核
     * @param pictureReviewRequest
     * @param loginUser
     */
    @Override
    public void doPicture(PictureReviewRequest pictureReviewRequest, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.PARAMS_ERROR);
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null ||PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 判断图片是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
        //校验审核状态是否重复
        if (oldPicture.getReviewStatus().equals(reviewStatus)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }
        // 数据库操作
        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean b = this.updateById(updatePicture);
        if (!b){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "数据更新失败");
        }
    }

    /**
     * 填充审核参数
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser){
        if (userService.isAdmin(loginUser)){
            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());
        }else {
            // 普通用户都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }

    /**
     * 批量抓取和创建图片
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        // 校验参数
        String searchText = pictureUploadByBatchRequest.getSearchText();
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        Integer count = pictureUploadByBatchRequest.getCount();
        if (count > 30){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最多抓取30条");
        }
        // 名称前缀默认值
        if (StrUtil.isBlank(namePrefix)){
            namePrefix = searchText;
        }
        // 抓取内容
        String url = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;
        try {
            document = Jsoup.connect(url).get();

        } catch (IOException e) {
            log.error("失败：{}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取页面失败");
        }
        // 解析内容
        Element firstDiv = document.getElementsByClass("dgControl").first();
        if (ObjUtil.isEmpty(firstDiv)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取图片失败");
        }
        assert firstDiv != null;
        Elements elements = firstDiv.select("img.mimg");
        // 遍历元素，依次上传图片
        int uploadCount = 0;
        for (Element element : elements) {
            String imgUrl = element.attr("src");
            if (StrUtil.isBlank(imgUrl)){
                log.info("当前连接{}为空，跳过", imgUrl);
                continue;
            }
            // 处理图片的地址，防止转义错误
            int questionIndex = imgUrl.indexOf("?");
            if (questionIndex > -1){
                imgUrl = imgUrl.substring(0, questionIndex);
            }
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(imgUrl);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            // 上传图片
            try {
                PictureVO pictureVO = this.uploadPicture(imgUrl, pictureUploadRequest, loginUser);
                log.info("上传图片成功, id = {}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e){
                log.error("图片上传失败{}", e.getMessage());
                continue;
            }
            if (uploadCount >= count){
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 清理图片
     * @param picture
     */
    @Async
    @Override
    public void clearPicture(Picture picture) {
        // 判断图片是否呗多条记录使用
        String url = picture.getUrl();
        Long count = this.lambdaQuery().eq(Picture::getUrl, url).count();
        if (count > 1){
            return;
        }
        try {
            // 删除图片
            obsManager.delObject(url);
            // 删除缩略图
            String thumbnailUrl = picture.getThumbnailUrl();
            if (StrUtil.isNotBlank(thumbnailUrl)){
                obsManager.delObject(thumbnailUrl);
            }
        } catch (IOException e) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除图片失败");
        }
    }

    /**
     * 删除图片
     * @param deleteRequest
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePicture(DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null ||  deleteRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获取代理对象
        PictureService pictureServiceProxy = (PictureService) AopContext.currentProxy();
        User loginUser = userService.getLoginUser(request);
        Long id = deleteRequest.getId();
        Picture picture = pictureServiceProxy.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.OPERATION_ERROR, "图片不存在");
        Long spaceId = picture.getSpaceId();
        // 仅仅本人和管理员可以删除图片
        pictureServiceProxy.checkPictureAuth(picture, loginUser);
        // 操作数据库
        boolean removeById = pictureServiceProxy.removeById(id);
        pictureServiceProxy.clearPicture(picture);
        // 更新额度
        boolean saved = pictureServiceProxy.saveOrUpdate(picture);
        ThrowUtils.throwIf(!saved, ErrorCode.OPERATION_ERROR, "数据保存失败");
        boolean update = spaceService.lambdaUpdate()
                .eq(Space::getId, spaceId)
                .setSql("totalSize = totalSize -" + picture.getPicSize())
                .setSql("totalCount = totalCount - 1")
                .update();
        if (!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数据保存失败");
        }
        ThrowUtils.throwIf(!removeById, ErrorCode.SYSTEM_ERROR, "删除失败");
    }

    /**
     * 校验图片权限
     * @param picture
     * @param loginUser
     */
    @Override
    public void checkPictureAuth(Picture picture, User loginUser) {
        Long spaceId = picture.getSpaceId();
        Long userId = loginUser.getId();
        if (spaceId == null){
            // 公共图库，仅本人或者管理员可以操作
            if (!picture.getUserId().equals(userId) && !userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }else {
            // 私有空间
            if (!picture.getUserId().equals(userId)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
    }

    /**
     * 根据颜色搜索图片
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 校验参数
        ThrowUtils.throwIf(spaceId == null || StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        // 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");

        if (!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 查询空间下的所有图片
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNull(Picture::getPicColor)
                .list();
        if (CollUtil.isEmpty(pictureList)){
            return new ArrayList<>();
        }
        // 将颜色字符串转化为主色调
        Color color = Color.decode(picColor);
        // 计算相似度并排序
        List<Picture> sortedPictureList = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
                    // 计算相似度
                    String hexColor = picture.getPicColor();
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 计算相似度
                    double similarity = CalculateColorUtil.calculateSimilarity(color, pictureColor);
                    return -similarity;
                })).limit(12)
                .collect(Collectors.toList());
        // 返回结果
        return sortedPictureList.stream().map(PictureVO::objToVo).collect(Collectors.toList());
    }

    /**
     * 批量编辑图片
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @Override
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        String category = pictureEditByBatchRequest.getCategory();
        List<String> tags = pictureEditByBatchRequest.getTags();
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList), ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);

        // 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有访问空间的权限");
        }
        // 查询指定图片
        List<Picture> pictureList = this.lambdaQuery()
                .select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIdList)
                .list();
        if (pictureList.isEmpty()){
            return;
        }
        // 更新分类和标签
        pictureList.forEach(picture -> {
            picture.setCategory(category);
            if (CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList, nameRule);
        // 擦偶作数据库进行批量更新
        boolean batchById = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!batchById, ErrorCode.SYSTEM_ERROR, "批量编辑失败");
    }

    /**
     * 创建扩图任务
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureExpandTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null, ErrorCode.PARAMS_ERROR);
        // 从数据库中根据id查询图片
        Picture picture = this.getById(pictureId);
        // 校验权限
        checkPictureAuth(picture, loginUser);
        // 创建扩图任务
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        createOutPaintingTaskRequest.setParameters(createOutPaintingTaskRequest.getParameters());
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        createOutPaintingTaskRequest.setInput(input);
        input.setImageUrl(picture.getUrl());
        // 创建任务
        CreateOutPaintingTaskResponse task = AliYunAiApi.createTask(createOutPaintingTaskRequest);
        return task;

    }

    /**
     * 批量填充信息
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || CollUtil.isEmpty(pictureList)){
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误");
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "操作失败");
        }
    }
}




